package com.example.cardgame

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    private val PICK_IMAGE = 1
    private val TAKE_PHOTO = 2

    private lateinit var imgAvatar: ImageView
    private lateinit var txtName: TextView
    private lateinit var txtGender: TextView
    private lateinit var txtPhone: TextView
    private lateinit var txtHighScore: TextView
    private lateinit var btnEditInfo: Button
    private lateinit var btnStartGame: Button

    private lateinit var editInfoLauncher: ActivityResultLauncher<Intent>
    private lateinit var gameLauncher: ActivityResultLauncher<Intent>

    private var highScore: Int = 0

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 绑定UI组件
        imgAvatar = findViewById(R.id.img_avatar)
        txtName = findViewById(R.id.txt_name)
        txtGender = findViewById(R.id.txt_gender)
        txtPhone = findViewById(R.id.txt_phone)
        txtHighScore = findViewById(R.id.txt_high_score)
        btnEditInfo = findViewById(R.id.btn_edit_info)
        btnStartGame = findViewById(R.id.btn_start_game)

        // 设置头像点击事件，允许选择图片或拍照
        imgAvatar.setOnClickListener {
            val options = arrayOf(
                getString(R.string.choose_from_gallery),
                getString(R.string.take_photo)
            )
            val builder = android.app.AlertDialog.Builder(this@MainActivity)
            builder.setTitle(getString(R.string.set_avatar))
                .setItems(options) { _, which ->
                    when (which) {
                        0 -> {
                            // 选择图片
                            val pickPhoto = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
                            startActivityForResult(pickPhoto, PICK_IMAGE)
                        }
                        1 -> {
                            // 拍照
                            val takePicture = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                            startActivityForResult(takePicture, TAKE_PHOTO)
                        }
                    }
                }
                .show()
        }

        // 初始化修改信息的 ActivityResultLauncher
        editInfoLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                val data = result.data
                if (data != null) {
                    val newName = data.getStringExtra("newName")
                    val newGender = data.getStringExtra("newGender")
                    val newPhone = data.getStringExtra("newPhone")

                    // 更新UI
                    txtName.text = newName
                    txtGender.text = newGender
                    txtPhone.text = newPhone
                }
            }
        }

        // 编辑信息按钮点击事件
        btnEditInfo.setOnClickListener {
            // 启动 EditInfoActivity 并传递当前的用户信息
            val intent = Intent(this@MainActivity, EditInfoActivity::class.java)
            intent.putExtra("currentName", txtName.text.toString())
            intent.putExtra("currentGender", txtGender.text.toString())
            intent.putExtra("currentPhone", txtPhone.text.toString())
            editInfoLauncher.launch(intent)
        }



        // 初始化游戏的 ActivityResultLauncher
        gameLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                val score = result.data?.getIntExtra("finalScore", 0) ?: 0
                // 如果当前分数大于最高分，更新最高分
                if (score > highScore) {
                    highScore = score
                    txtHighScore.text = "$highScore"
                }
            }
        }

        // 开始游戏按钮点击事件
        btnStartGame.setOnClickListener {
            val intent = Intent(this@MainActivity, GameActivity::class.java)
            gameLauncher.launch(intent)
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (resultCode == RESULT_OK) {
            when (requestCode) {
                PICK_IMAGE -> {
                    val selectedImage: Uri? = data?.data
                    selectedImage?.let {
                        val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, it)
                        imgAvatar.setImageBitmap(bitmap) // 设置头像为选择的图片
                    }
                }
                TAKE_PHOTO -> {
                    val photo = data?.extras?.get("data") as? Bitmap
                    photo?.let {
                        imgAvatar.setImageBitmap(it) // 设置头像为拍摄的照片
                    }
                }
            }
        } else {
            Toast.makeText(this, getString(R.string.action_canceled), Toast.LENGTH_SHORT).show()
        }
    }
}
